package com.liu.webstore.service.impl;

import com.liu.webstore.service.DataService;
import com.liu.webstore.util.RedisKeyUtil;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author LiuYumei
 * @Date 2022/8/28 21:41
 */
@Service
public class DataServiceImpl implements DataService {
    @Autowired
    private RedisTemplate redisTemplate;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 将指定的IP计入UV
     *
     * @param ip（用户IP）
     */
    @Override
    public void recordUV(String ip) {
        String uvKey = RedisKeyUtil.getUVKey(sdf.format(new Date()));
        redisTemplate.opsForHyperLogLog().add(uvKey, ip);
    }

    /**
     * 统计指定日期范围内的UV
     */
    @Override
    public long calculateUV(Date start, Date end) {
        Asserts.check(Objects.isNull(start) || Objects.isNull(end), "参数不能为空！");
        // 整理该日期范围内的key
        List<String> uvList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)) {
            String key = RedisKeyUtil.getUVKey(sdf.format(calendar.getTime()));
            uvList.add(key);
            calendar.add(Calendar.DATE, 1);
        }

        // 合并数据
        String uvKey = RedisKeyUtil.getUVKey(sdf.format(start), sdf.format(end));
        redisTemplate.opsForHyperLogLog().union(uvKey, uvList.toArray());

        // 返回统计结果
        return redisTemplate.opsForHyperLogLog().size(uvKey);
    }

    /**
     * 统计指定的用户ID计入DAU
     *
     * @param userId（用户ID）
     */
    @Override
    public void recordDAU(int userId) {
        String dauKey = RedisKeyUtil.getDAUKey(sdf.format(new Date()));
        redisTemplate.opsForValue().setBit(dauKey, userId, true);
    }

    @Override
    public long calculateDAU(Date start, Date end) {
        Asserts.check(Objects.isNull(start) || Objects.isNull(end), "参数不能为空！");
        List<byte[]> dauList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)) {
            String dauKey = RedisKeyUtil.getDAUKey(sdf.format(calendar.getTime()));
            dauList.add(dauKey.getBytes());
            calendar.add(Calendar.DATE, 1);
        }
        // 进行OR运算
        return (long) redisTemplate.execute((RedisCallback) redisConnection -> {
            String dauKey = RedisKeyUtil.getDAUKey(sdf.format(start), sdf.format(end));
            redisConnection.bitOp(RedisStringCommands.BitOperation.OR,
                    dauKey.getBytes(), dauList.toArray(new byte[0][0]));
            return redisConnection.bitCount(dauKey.getBytes());
        });
    }
}
